<?php
ob_start();

session_start();
require_once('../../config.php');
require_once('../photo_save.php');

$regfixicon = name_fixed_icon;
// Code for Session Cookie workaround
	if (isset($_POST["PHPSESSID"])) {
		session_id($_POST["PHPSESSID"]);
	} else if (isset($_GET["PHPSESSID"])) {
		session_id($_GET["PHPSESSID"]);
	}
	$dir='';
	if (isset($_POST["folder_upload"])) {
		$dir = ($_POST["folder_upload"]);
		$save_path =  $dir."/";
	} else if (isset($_GET["folder_upload"])) {
		$dir = ($_GET["folder_upload"]);
		$save_path =  $dir."/";
	}

	if (isset($_POST["id"])) {
		$id = ($_POST["id"]);
	} else if (isset($_GET["id"])) {
		$id = ($_GET["id"]);
	}

	if($dir==''){
		$dir='uploads';
		$save_path =  getcwd()."/".$dir."/";
	}
	
function HandleError($message) {
	echo $message;
}
	$_SESSION['isupload'] = true;
// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
	$POST_MAX_SIZE = ini_get('post_max_size');
	$unit = strtoupper(substr($POST_MAX_SIZE, -1));
	$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

	if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
		header("HTTP/1.1 500 Internal Server Error");
		echo "POST exceeded maximum allowed size.";
		exit(0);
	}

// Settings
	
	//$save_path =  getcwd()."/".$dir."/"; //getcwd() . "/uploads/";				// The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
	$upload_name = "Filedata";
	$max_file_size_in_bytes = 52000000;				// 2Gb in bytes 1.024.000 = 1Mb
	$extension_whitelist = array("jpg","JPG", "gif", "png");	// Allowed file extensions
	$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';				// Characters allowed in the file name (in a Regular Expression format)
	
// Other variables	
	$MAX_FILENAME_LENGTH = 260;
	$file_name = "";
	$file_extension = "";
	$uploadErrors = array(
        0=>"There is no error, the file uploaded with success",
        1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
        2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
        3=>"The uploaded file was only partially uploaded",
        4=>"No file was uploaded",
        6=>"Missing a temporary folder"
	);



// Validate the upload
	if (!isset($_FILES[$upload_name])) {
		HandleError("No upload found in \$_FILES for " . $upload_name);
		exit(0);
	} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
		HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
		exit(0);
	} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
		HandleError("Upload failed is_uploaded_file test.");
		exit(0);
	} else if (!isset($_FILES[$upload_name]['name'])) {
		HandleError("File has no name.");
		exit(0);
	}


// Validate the file size (Warning the largest files supported by this code is 2GB)
	$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
	if (!$file_size || $file_size > $max_file_size_in_bytes) {
		HandleError("File exceeds the maximum allowed size");
		exit(0);
	}
	
// Validate file extention
	$path_info = pathinfo($_FILES[$upload_name]['name']);
	$file_extension = $path_info["extension"];
	$is_valid_extension = false;
	foreach ($extension_whitelist as $extension) {
		if ($file_extension == $extension) {
			$is_valid_extension = true;
			break;
		}
	}
	if (!$is_valid_extension) {
		HandleError("Invalid file extension");
		exit(0);
	}

// Validate file name (for our purposes we'll just remove invalid characters)
	$origin_name = pathinfo($_FILES[$upload_name]['name'], PATHINFO_FILENAME);
	$file_name = md5(uniqid($origin_name)).'.'.$file_extension;
	if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) {
		HandleError("Invalid file name");
		exit(0);
	}

// Validate that we won't over-write an existing file
/*	if (file_exists($save_path . $file_name)) {
		HandleError("File with this name already exists");
		exit(0);
	}
*/

// Process the file
	/*
		At this point we are ready to process the valid file. This sample code shows how to save the file. Other tasks
		 could be done such as creating an entry in a database or generating a thumbnail.
		 
		Depending on your server OS and needs you may need to set the Security Permissions on the file after it has
		been saved.
	*/
	if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
		HandleError("File could not be saved: ". $save_path.$file_name);
		exit(0);
	}

// Return output to the browser (only supported by SWFUpload for Flash Player 9)

	echo "File Received ". $save_path.$file_name;

	// Get the image and create a THUMBNAIL
	
    if (extension_loaded("gd") && file_exists("".$save_path.$file_name."")) { 
		
		$img = imagecreatefromjpeg($save_path.$file_name);
		$new_file_name = $regfixicon.$file_name;

		$width = imagesx($img);
		$height = imagesy($img);
	
		if (!$width || !$height) {
			HandleError ("ERROR:Invalid width or height");
			exit(0);
		}
	
		// Build the thumbnail
		$target_width = 140;
		$target_height = 105;
		$target_ratio = $target_width / $target_height;
	
		$img_ratio = $width / $height;
	
		if ($target_ratio > $img_ratio) {
			$new_height = $target_height;
			$new_width = $img_ratio * $target_height;
		} else {
			$new_height = $target_width / $img_ratio;
			$new_width = $target_width;
		}
	
		if ($new_height > $target_height) {
			$new_height = $target_height;
		}
		if ($new_width > $target_width) {
			$new_height = $target_width;
		}
		$new_img = imagecreatetruecolor(140, 105);
		$transparent = imagecolorallocatealpha($img, 255,255,255, 127);
		$white = imagecolorallocate($new_img, 255, 255, 255);
		if (!@imagefilledrectangle($new_img, 0, 0, $target_width-1, $target_height-1, $transparent)) {	// Fill the image color bg
			HandleError("ERROR:Could not fill new image");
			exit(0);
		}
	
		if (!@imagecopyresampled($new_img, $img, ($target_width-$new_width)/2, ($target_height-$new_height)/2, 0, 0, $new_width, $new_height, $width, $height)) {
			HandleError("ERROR:Could not resize image");
			exit(0);
		}
		imagejpeg($new_img, $save_path.$new_file_name, 70); 
		imagedestroy($new_img);    


		// Resize pic
	/*	$flag = false;
		
		$target_width = 800;
		$target_height = 550;
		if($width>$height && $width>$target_width){
			$new_width = $target_width;
			$new_height = $target_width*($height/$width);
			$flag = true;
		}
		else if($height>$width && $height>$target_height){
			$new_height = $target_height;
			$new_width = $target_height*($width/$height);
			$flag = true;
		}
		
		if(!$flag){
			if($width>=500 && $width>$height && $height>200){ // truong hop lon hon ca 2 chieu
				$watermark = @imagecreatefrompng('images/watermark.png'); 
			}
			else if($height>=450 && $height>$width && $width>200){ // truong hop lon hon chieu dung, hep chieu ngang 
				$watermark = @imagecreatefrompng('images/watermarkH.png'); 
			}
			else{ // truong hop hep cả 2 chieu 
				$watermark = @imagecreatefrompng('images/watermark-s.png'); 
			}
		} else {
			if($new_width>=500 && $new_width>$new_height && $new_width>200){ // truong hop lon hon ca 2 chieu
				$watermark = @imagecreatefrompng('images/watermark.png'); 
			}
			else if($new_height>=450 && $new_height>$new_width && $new_width>200){ // truong hop lon hon chieu dung, hep chieu ngang 
				$watermark = @imagecreatefrompng('images/watermarkH.png'); 
			}
			else{ // truong hop hep cả 2 chieu 
				$watermark = @imagecreatefrompng('images/watermark-s.png'); 
			}		
		}
		
		$watermarkwidth =  imagesx($watermark); 
		$watermarkheight =  imagesy($watermark); 
		if($flag){
			$dest_img = imagecreatetruecolor($new_width, $new_height); 
			imagecopyresampled($dest_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
			imagejpeg($dest_img, $save_path.$file_name, 100); 
			$width = imagesx($dest_img);
			$height = imagesy($dest_img);
		} 
		$startwidth = ($width - $watermarkwidth); 
		$startheight = ($height - $watermarkheight); 

		if($flag){
			imagecopy($dest_img, $watermark,  $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight); 
			imagejpeg($dest_img, $save_path.$file_name, 100); 
			imagedestroy($dest_img);
		} else {
			imagecopy($img, $watermark,  $startwidth, $startheight, 0, 0, $watermarkwidth, $watermarkheight); 
			imagejpeg($img, $save_path.$file_name, 100); 
		}
		imagedestroy($img); 
		imagedestroy($watermark); */

	}
	save_image($id, $file_name, $origin_name);
	
	$_SESSION['isupload'] = false;

ob_end_flush();

?>